#include <signal.h>

#include <iostream>
using namespace std;

#include "NetworkManager.h"
#include "Processor.h"
#include "ParamManager.h"

#ifdef _WIN32
#ifdef _DEBUG
	#include <crtdbg.h>
	#undef THIS_FILE
	static char THIS_FILE[] = __FILE__;
	#define new       new( _NORMAL_BLOCK, __FILE__, __LINE__)
	#define malloc(s) _malloc_dbg(s, _NORMAL_BLOCK, __FILE__, __LINE__)
#endif
#endif

// global used to catch a ctrl-c signal (extern defined in 'dispatch_s.h')
bool _intHandler = false;

// called when 'ctrl-c' is caught
void intHandler(int dummy = 0) {
	// global variable set when 'ctrl-c' is caught
	_intHandler = true;
}

int main(int argc, char* argv[]) {
	// catch process interrupt, and save out state information
	signal(SIGINT, intHandler);
//	signal(SIGKILL, intHandler);

	// load 'port' from the settings file
	TCHAR s_port[DEFAULT_BUFLEN];
	GetPrivateProfileString(
				TEXT("default"),
				TEXT("port"),
				"2244",	// default value if not found
				s_port,
				DEFAULT_BUFLEN,
				".\\dispatch_s.ini");

	// Start up a network handler
	NetworkManager nm;
	Connection *c;

	// Establish server listening port
	c = nm.add();
	c->settings.set("isListen", "true");
	c->settings.set("port", s_port);
	nm.start(c);

	// Create a new processor
	Processor processor(nm);

	// Long as the Network Manager is still listening, keep going.
	while(true) {
		// wait forever until network activity
		nm.waitForReady();

		// process the network activity
		if(nm.isNew()) {
			while(c = nm.getNewConnection()) {
#ifdef _DEBUG
				printf("[%d] New connection added.\n", c->socket);
#endif // _DEBUG
			}
		}
		else if(nm.isData()) {
			while(c = nm.getDataConnection()) {
#ifdef _DEBUG
				printf("[%d] Recv: %s\r\n", c->socket, c->bm->getNext());
#endif // _DEBUG
				// process the incoming data from the client
				processor.start(c);

				// pop off the current data
				c->bm->pop();

				// Catch a Ctrl-C interrupt
				if(_intHandler) {
					break;
				}
			}
		}
		else if(nm.isDel()) {
			while(c = nm.getDelConnection()) {
#ifdef _DEBUG
				printf("[%d] Connection dropped.\n", c->socket);
#endif // _DEBUG
				nm.del(c);
			}
		}
		else {
			// Heartbeat Activities / AKA When there is no network traffic

		}

		// Catch a Ctrl-C interrupt
		if(_intHandler) {
			break;
		}
	}

	// Process is exiting
}